local blaze = require "blaze"
local app = require "app"

local M = {}

local searchers = {}
local searchers_by_package = {}

local function search(t, k)
    for _, searcher in ipairs(searchers) do
        local ret = searcher(t, k)
        if ret then
            return ret
        end
    end
end

local function add_searcher(package)
    assert(not searchers_by_package[package])
    local searcher = function(t, name)
        local path = string.format("%s.config.%s", package, name)
        local ok, result
        if blaze.package_exists(path) then
            ok, result = pcall(require, path)
            if ok then
                rawset(t, name, result)
                return result
            else
                error(string.format("load config %s error:%s", name, result))
            end
        end
    end
    table.insert(searchers, searcher)
end

local function remove_searcher(package)
    local searcher = searchers_by_package[package]
    if not searcher then
        return
    end
    for i, v in ipairs(searchers) do
        if v == searcher then
            table.remove(searchers, i)
            searchers_by_package[package] = nil
            return
        end
    end
end

function M.init()
    M._package = app.game.running.package
    add_searcher(M._package)
    add_searcher("club.threecard.gamelib")
end

function M.release()
    remove_searcher(M._package)
    remove_searcher("club.threecard.gamelib")
end

M.searchers = searchers
M.add_searcher = add_searcher
M.remove_searcher = remove_searcher

return setmetatable(M, { __index = function(t, k)
    return search(t, k) or app.store[k]
end})